package com.ovo.dailypayaccount.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description http请求工具类
 * @Author wubin
 * @Date 2019-07-28 13:20
 * @Version 1.0
 **/
public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static final String CHAR_SET = "UTF-8";
    /**
     * post请求
     */
    public static JSONObject doPost(String url, Map<String, String> params) {
        JSONObject json = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            // 设置请求和传输超时时间30秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头参数
            httpPost.setHeader("dealer-id", "12345678");//代码
//            httpPost.setHeader("request-id", IdGen.uuid());// request的 id
            // 设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if(params!=null&&!params.isEmpty()){
                for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
                    String name = (String) iter.next();
                    String value = String.valueOf(params.get(name));
                    nvps.add(new BasicNameValuePair(name, value));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            logger.info("doPost请求url:" + httpPost.toString());
            // 执行post请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String respStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            json = JSON.parseObject(respStr);
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * get请求
     */
    public static JSONObject doGet(String url, Map<String, String> params) {
        JSONObject json = null;
        try {
            StringBuffer urlBuffer = new StringBuffer(url);
            if(params!=null&&!params.isEmpty()){
                // 设置参数
                Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
                urlBuffer.append("?");
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    Object key = entry.getKey();
                    urlBuffer.append(key);
                    urlBuffer.append('=');
                    String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");//参数加密
                    urlBuffer.append(value);
                    if (it.hasNext()) {
                        urlBuffer.append("&");
                    }
                }
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(urlBuffer.toString());
            logger.info("doGet请求url:" + urlBuffer.toString());
            // 设置请求和传输超时时间30秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            // 设置请求头参数
//            httpGet.setHeader("dealer-id", "12345678");//代码
////            httpGet.setHeader("request-id", IdGen.uuid());// request的 id
            // 执行get请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String respStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            json = JSON.parseObject(respStr);
            logger.info("doGet请求，返回:" + json.toString());
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * get请求,返回字符串
     */
    public static String doGetString(String url, Map<String, String> params) {
        String respStr = null;
        try {
            StringBuffer urlBuffer = new StringBuffer(url);
            if(params!=null&&!params.isEmpty()){
                // 设置参数
                Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
                urlBuffer.append("?");
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    Object key = entry.getKey();
                    urlBuffer.append(key);
                    urlBuffer.append('=');
                    String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");//参数加密
                    urlBuffer.append(value);
                    if (it.hasNext()) {
                        urlBuffer.append("&");
                    }
                }
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(urlBuffer.toString());
            logger.info("doGetString请求url:" + urlBuffer.toString());
            // 设置请求和传输超时时间30秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            // 设置请求头参数
//            httpGet.setHeader("dealer-id", "12345678");//代码
////            httpGet.setHeader("request-id", IdGen.uuid());// request的 id
            // 执行get请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            respStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("doGetString请求，返回:" + respStr);
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respStr;
    }
    public String sendJsonPost(String url, String param){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseContent = null;
        try {
            logger.info("梦网短信发送请求："+url+param);
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(param, Charset.forName(CHAR_SET)));
            response = httpClient.execute(httpPost);
            HttpEntity entity = (HttpEntity) response.getEntity();
            responseContent = EntityUtils.toString((org.apache.http.HttpEntity) entity, CHAR_SET);
        }catch(Exception e) {
            logger.error("梦网短信发送请求"+url+"异常："+e.getMessage());
            e.printStackTrace();
        }finally {
            try {
                if (response != null) response.close();
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                logger.error("关闭请求"+url+"异常："+e.getMessage());
                e.printStackTrace();
            }

        }
        return responseContent;
    }
}
